<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div v-loading="infoLoading" class="sign-detail-container no-margin mobile-radius">
      <template v-if="!permissionDenied">
        <ProgressStep v-if="!showMobilePage" :mode="2" :step-list="stepList" :order-status="stepActiveId" :is-show-correct="false" :is-expedited="signUpInfo.isExpedited"/>
        <explanation :explanation="explanationObj" :countdown="true" :style="`${showMobilePage ? 'margin-bottom: 0px' : ''}`" @queryProcessData="queryProcessData"/>
        <div :style="`${showMobilePage ? 'padding-top: 8px' : ''}`" class="sign-detail-content small-padding">
          <Title title="供应商信息" style="font-size:16px; margin:16px 0"/>
          <supplierInfo ref="supplierInfo" :supplier-info="signUpInfo" :show-mobile-page="showMobilePage"/>
          <div class="account-header">
            <Title title="收款账户" style="font-size:16px"/>
          </div>
          <paymentInfo v-if="flag" ref="paymentInfo" :channel-name="signUpInfo.channelName" :account-list-data="signUpInfo.accountsReceivable.list" :account-list="signUpInfo.supplierType===0?personAccount:companyAccount"/>
          <Title title="账号信息" style="font-size:16px; margin:32px 0 0"/>
          <div v-if="showAccountInfo">
            <DetailTabs v-model="activeTab" :tabs="accountTabs" class="list-tab" @tabClick="handleTabClick" />
            <accountInfo
              ref="accountInfo"
              :sign-up-id="signUpId"
              :id="accountsInfoItem.id"
              :accounts-info-item="accountsInfoItem"
              :sign-status="accountsInfoItem.signStatus"
              :sign-detail-status="accountsInfoItem.signDetailStatus"
              :process-finished="stepActiveId === PROGRESS_STEP.FINISHED"
              :operation-set-events="operationSetEvents"
              :process-list="processData.list"
              :status="processData.processStatus"
              :additional-key="accountsInfoItem.additionalKey"
              :accounts-info="accountsInfoItem.accountsInfo"
              :price-info="accountsInfoItem.priceInfo"
              :contract-list="accountsInfoItem.contractList"
              :show-mobile-page="showMobilePage"
              :contract-info="accountsInfoItem.contractInfo"
              :sign-manage-info="accountsInfoItem.signManageInfo"
              :show-associate-btn="showRelatedGroupBtn"
              @refreshData="refreshSignUpInfo"
              @onContractSelect="confirmRelatedContract"/>
          </div>
          <div v-else class="empty-container">
            <img :src="emptyIcon" alt="">
            <div class="text">暂无账号信息</div>
          </div>
          <el-image v-if="isRevoke" :src="revokeImg" class="revoke-img"/>
        </div>

        <ExamineAndApprove
          ref="examineAndApproveRef"
          :disabled="infoLoading"
          :show-print="false"
          :process-id="processId"
          :main-id="signUpId"
          :version="version"
          :get-comments-api="getsignUpComments"
          :comment-add-api="signUpCommentAdd"
          :process-revocation-api="signUpProcessRevocation"
          :process-recall-api="signUpProcessRecall"
          :process-audit-api="signUpProcessAudit"
          :create-user="createUser"
          :business-type="BUSINESS_TYPE.SIGNUP"
          :process-type="PROCESS_TYPE.SIGNUP"
          :audit-schedule-data="auditScheduleData"
          :senders="senders"
          :default-aduitor-list="[createUser]"
          :approval-module-type="APPROVAL_MODULE_TYPE.SIGN_UP"
          :show-renewal-contract="!!allAutoRenewalAccounts.length"
          :show-resource-syncbtn="showResourceSyncBtn"
          next-approve-module-id="signUpId"
          redirect-url="/supplierPage/signUpDetail"
          detail-page-router-name="signUpDetail"
          edit-page-router-name="signUpEdit"
          @toBack="toBack"
          @setProcessData="setProcessData"
          @handlePressSend="handlePressSend"
          @getAuditSchedule="getAuditSchedule"
          @queryProcessData="queryProcessData"
          @handleCreateNew="handleCreateNew('signUpEdit',{id: signUpId},{reapplyId: processId})"
          @handleSendMsg="handleSendMsg"
          @handleSender="handleSender"
          @handleModify="handleModify('signUpEdit',{id: signUpId},{remodifyId: processId})"
          @handleCancelPress="handleCancelPress"
          @handleSignUpSync="handleSignUpSync"
        >
          <div v-if="showRelatedGroupBtn" slot="signUp">
            <el-dropdown trigger="click" placement="top">
              <el-button type="primary" size="small" style="height: 32px;">关联合同</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="relatedContractShow">关联现有合同</el-dropdown-item>
                <el-dropdown-item class="flex-center" @click.native="checkAccountSync">发起合同审批<tipIcon class="ml5" content="若为新账号，需要先同步资源后，才可发起合同审批"/></el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </ExamineAndApprove>
      </template>
      <DeniedPlaceholder v-else />
      <ding-ding-dialog
        ref="pressSendDialogRef"
        :btn1="'确认加急'"
        :btn2="'取消'"
        :show-send-checkbox="false"
        :select-with-user-load="false"
        :default-list="pressDefaultList"
        redirect-url="/supplierPage/signUpDetail"
        summary-title="加急原因"
        title="催办通知"
        @handelOK="toSend" />
    </div>
    <AccountSync ref="accountSyncRef" :process-id="Number(processId)"/>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="closeDialog"
      :show-close="true"
      :append-to-body="true"
      :class="{'mobile-el-dialog': showMobilePage}"
      center
      width="320px"
      class="limit-dialog"
      @close="closeDialog"
    >
      <div class="top-title">
        <img :src="tipImg" alt="tip_icon">
        <div>
          <p class="top-text">关联合同确认</p>
          <p class="top-sub-text">确认关联后，合同有效期将覆盖签约有效期</p>
        </div>
      </div>
      <div class="dialog-center">
        <div class="mb16"><span>签约有效期：</span>{{ formatSignDate(accountsInfoItem.contractInfo,'YYYY/MM/DD') }}</div>
        <div><span>合同有效期：</span>{{ formatValidDate(contractData,'YYYY/MM/DD') }}</div>
      </div>
      <div class="flex dialog-footer">
        <el-button class="ok" type="primary" size="small" @click="handleOk">关联并覆盖</el-button>
        <el-button class="cancel-btn-style" type="info" size="small" @click="closeDialog">取消关联</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 组件
import ListTab from '@/components/ListTab';
import ProgressStep from '@/components/CreateOrder/orderDetail/step';
import supplierInfo from '@/views/signUp/components/supplierInfo';
import accountInfo from '@/views/signUp/components/accountInfo';
import paymentInfo from '@/views/signUp/components/paymentInfo';
import Title from '@/components/Title';
import explanation from '@/components/Common/explanation';
import ExamineAndApprove from '@/components/Common/ExamineAndApprove';
import AccountSync from '../components/accountSync';
// 工具函数
import { mapState } from 'vuex';
import { PROGRESS_STEP } from '@/utils/const/energy';
import { BUSINESS_TYPE, PROCESS_TYPE, EVENT_TYPE } from '@/utils/const/process';
import { hasRouteAuth } from '@/utils/permission';
import { APPROVAL_MODULE_TYPE } from '@/utils/const';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import { personAccount, companyAccount } from '@/views/signUp/components/data';
import { SIGN_DETAIL_STATUS } from '@/utils/const/resouce';
// 图片
import revokeImg from '@/assets/auditProcess/process_status_3.png';
import emptyIcon from '@/assets/home/emptyIcon.png';
import tipImg from '@/assets/customer/tip_icon.png';
// API
import {
  signUpDetail,
  getsignUpComments,
  signUpCommentAdd,
  signUpProcessRevocation,
  signUpProcessRecall,
  signUpProcessAudit,
  checkAccountSync,
  associateAccountContract
} from '@/api/signUp';
import schedule from '@/mixins/schedule';
import { format } from '@/filters/date';

export default {
  components: {
    ListTab,
    ProgressStep,
    supplierInfo,
    accountInfo,
    paymentInfo,
    Title,
    explanation,
    ExamineAndApprove,
    AccountSync,
    DetailTabs
  },
  mixins: [schedule],
  data() {
    return {
      APPROVAL_MODULE_TYPE,
      flag: true,
      personAccount,
      companyAccount,
      revokeImg,
      emptyIcon,
      tipImg,
      signUpId: '', // 签约单id
      processId: '', // 流程id
      signUpInfo: {
        accountsReceivable: {},
        accountsInfoList: []
      },
      infoLoading: false,
      BUSINESS_TYPE,
      PROGRESS_STEP,
      PROCESS_TYPE,
      getsignUpComments,
      signUpCommentAdd,
      signUpProcessRevocation,
      signUpProcessRecall,
      signUpProcessAudit,
      permissionDenied: false, // 详情页是否可查看
      hasLegalCode: false, // 是否发起合同
      activeTab: '',
      accountTabs: [], // 账户列表
      stepActiveId: PROGRESS_STEP.PENDING,
      accountsInfoItem: {
        accountsInfo: {},
        priceInfo: {},
        contractInfo: {},
        signManageInfo: {},
        additionalKey: {}
      }, // 当前账号信息
      processData: {// 流程信息
        list: [],
        operation: {
          auth: [],
          content: null
        }
      },
      isRevoke: false,
      showResourceSyncBtn: true,
      showAssociateBtn: false,
      operationSetEvents: [],
      dialogVisible: false,
      contractData: {}
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isCreate() { // 创建人
      return this.userInfo.id === this.signUpInfo.creatorId;
    },
    stepList() {
      return [
        { name: '待提交', id: PROGRESS_STEP.PENDING },
        { name: '审批中', id: PROGRESS_STEP.UNDER_REVIEW },
        { name: '已完成', id: PROGRESS_STEP.FINISHED }
      ];
    },
    showAccountInfo() { // 展示账号信息
      return this.accountTabs.length > 0;
    },
    // showLegalApprove() { // 显示发起合同审批
    //   // return this.stepActiveId === PROGRESS_STEP.FINISHED && !this.hasLegalCode && !((this.signUpInfo.accountsInfoList || []).every(i => i.signStatus === -1));
    //   return this.stepActiveId === PROGRESS_STEP.FINISHED;
    // },
    createUser() {
      let user = { id: this.signUpInfo.creatorId, userName: this.signUpInfo.createUser };
      if (this.isCreate) {
        user = this.userInfo;
      }
      return user;
    },
    // 所有账号签约状态为自动续约的账号id，有符合条件的id更多操作展示<关联签约合同>按钮
    allAutoRenewalAccounts() {
      const { accountsInfoList } = this.signUpInfo;
      if (!accountsInfoList || !Array.isArray(accountsInfoList)) return [];
      const targetStatus = [SIGN_DETAIL_STATUS.SIGNED, SIGN_DETAIL_STATUS.RENEWAL, SIGN_DETAIL_STATUS.AUTO_RENEWAL];
      return accountsInfoList.filter(account => targetStatus.includes(account.signDetailStatus)).map(i => i.id) || [];
    },
    /**
     关联合同 & 发起合同审批 按钮同时显示隐藏判断
     1、没关联合同，且有开启事件的时候，两个按钮都显示
     2、没关联合同，没开启事件的时候，两个按钮都显示
     （多个账号若仅有一个未关联合同也属于未关联合同，显示按钮）
     3、有关联合同，有开启事件的时候，两个按钮都显示
     4、有关联合同，没开启事件的时候，两个按钮都不显示
     5、已作废审批单，两个按钮都不显示
    */
    showRelatedGroupBtn() {
      // 是否全部账号都有关联合同
      const hasLegalOfList = (this.signUpInfo.accountsInfoList || []).every(item => (Array.isArray(item.contractList) && item.contractList.length));
      return !this.isRevoke && (!hasLegalOfList || this.showAssociateBtn);
    }
  },
  watch: {
    'signUpInfo.supplierType': {
      handler: function() {
        this.flag = false;
        this.$nextTick(() => {
          this.flag = true;
        });
      },
      deep: true
    }
  },
  beforeDestroy() {
    window.removeEventListener('storage', (e) => {
      if (e.key === 'freshCreateSignUp') {
        this.initData();
      }
    });
  },
  created() {
    this.initData();
    window.addEventListener('storage', (e) => {
      if (e.key === 'freshCreateSignUp') {
        this.initData();
      }
    });
  },
  methods: {
    hasRouteAuth,
    format,
    initData() {
      this.initRouteData();
      this.queryProcessData(); // 流程数据
    },
    initRouteData() {
      this.signUpId = this.$route.query.signUpId;
      this.processId = this.$route.query.processId;
      if (!this.signUpId || !this.processId) {
        this.$message.warning('无法获取ID');
        const timer = setTimeout(() => {
          this.$router.back();
          clearTimeout(timer);
        }, 1500);
      }
    },
    handleTabClick(index) {
      this.activeTab = index;
      this.accountsInfoItem = this.signUpInfo.accountsInfoList[index];
    },
    setProcessData(processData) {
      this.processData = processData;
      this.operationSetEvents = processData.operation.setEvents;
      this.showAssociateBtn = this.operationSetEvents.includes(EVENT_TYPE.ASSOCIATE_CONTRACT); // 控制关联合同按钮的显示(开启关联合同事件)
    },
    // 获取基本信息
    querySignUpInfo(callback = () => {}) {
      this.infoLoading = true;
      if (!this.signUpId && this.signUpId !== 0) return;
      signUpDetail(this.signUpId).then(res => {
        this.infoLoading = false;
        this.handleProcessCheck(res.data.processId);
        if (res.code === 200) {
          if (res.data.processStatus === 3) { // 3为撤销
            this.isRevoke = true;
          } else {
            this.stepActiveId = res.data.processStatus;
            this.isRevoke = false;
          }
          this.hasLegalCode = res.data.createdContract || false;
          this.accountTabs = [];
          res.data.accountsInfoList && res.data.accountsInfoList.forEach((el, index) => { // 获取账号tab
            this.accountTabs.push({
              name: el.accountsInfo.accountName,
              id: index
            });
          });
          res.data.accountsReceivable && res.data.accountsReceivable.list.forEach(el => {
            if (el.province) {
              el.province = el.province.replace(/,/g, '-');
            }
          });
          this.signUpInfo = res.data;
          this.accountsInfoItem = res.data.accountsInfoList[0] || [];
          this.showResourceSyncBtn = !res.data.accountsInfoList.every(it => it.contractInfo.isExpired) && !this.isRevoke; // 控制同步资源按钮的显示
          if (this.accountTabs.length > 0) { this.activeTab = this.accountTabs[0].id; }
          callback && callback();
        }
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        callback && callback();
        this.infoLoading = false;
      });
    },
    refreshSignUpInfo() {
      const index = this.activeTab;
      this.querySignUpInfo(() => this.handleTabClick(index));
    },
    queryProcessData() {
      this.querySignUpInfo();
      this.getAuditSchedule();
      this.$nextTick(() => {
        this.$refs.examineAndApproveRef && this.$refs.examineAndApproveRef.getProcessList();
      });
    },
    // 发起合同审批前判断账号是否均已同步
    checkAccountSync() {
      checkAccountSync(this.signUpId).then(res => {
        if (res.code === 501) {
          this.$message.warning(res.message);
        } else if (res.code === 200) {
          const mediumIds = res.data && res.data.mediumIds || '';
          this.toLegalCreate(mediumIds);
        }
      });
    },
    // 发起合同审批
    toLegalCreate(mediumIds) {
      const url = this.$router.resolve({
        name: 'CreateContract',
        query: {
          type: 5,
          mediumIds,
          signUpId: this.signUpId,
          processId: this.processId
        }
      });
      window.open(url.href, '_blank');
    },
    toBack() {
      if (this.$route.query.fromTodo) {
        this.$router.go(-1);
      } else {
        this.$router.push({ name: 'signUp' });
      }
    },
    getAuditSchedule() {
      this.requestAuditSchedule(this.processId);
    },
    formatSignDate(data) {
      if (data.signStartDate || data.signEndDate) {
        return this.format(data.signStartDate, 'YYYY/MM/DD') + '-' + this.format(data.signEndDate, 'YYYY/MM/DD');
      } else {
        return '--';
      }
    },
    formatValidDate(data) {
      if (data.contractEffectStartDate || data.contractEffectEndDate) {
        return this.format(data.contractEffectStartDate, 'YYYY/MM/DD') + '-' + this.format(data.contractEffectEndDate, 'YYYY/MM/DD');
      } else {
        return '--';
      }
    },
    confirmRelatedContract(data) {
      this.contractData = data;
      if (!this.contractData.id) {
        this.$message.warning('无效合同，请重新选择');
        return;
      }
      if (data.contractEffectStartDate && data.contractEffectEndDate && this.accountsInfoItem.contractInfo && this.accountsInfoItem.contractInfo.signStartDate) {
        this.dialogVisible = true;
      } else {
        this.handleOk();
      }
    },
    handleOk() {
      const params = {
        contractId: this.contractData.id,
        accountId: this.accountsInfoItem.id
      };
      associateAccountContract(params).then(res => {
        res.code === 200 && this.$message.success('关联成功');
      }).finally(() => {
        this.closeDialog();
        const currActiveId = this.activeTab;
        this.querySignUpInfo(() => this.handleTabClick(currActiveId));
      });
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    // 同步账号资源
    handleSignUpSync() {
      if (!this.signUpInfo || !this.signUpInfo.accountsInfoList || !this.signUpInfo.accountsInfoList.length) {
        this.$message.warning('该审批不存在可同步的账号');
        return;
      }
      const { accountsInfoList } = this.signUpInfo;
      const list = [];
      accountsInfoList.forEach(item => {
        const accountData = { id: item.id, isExpired: item.contractInfo.isExpired };
        accountData.label = `${item.accountsInfo.accountName}(${item.accountsInfo.platformName})`;
        list.push(accountData);
      });
      this.$refs['accountSyncRef'].init(this.signUpId, list);
    },
    relatedContractShow() {
      this.$refs['accountInfo'].relatedContractShow();
    }
  }
};
</script>
<style lang="scss" scoped>
.sign-detail-container{
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding-bottom: 55px;
  min-height: calc(100vh - 64px);
  .sign-detail-content{
    position: relative;
    padding: 0 24px 56px;
  }
  &::v-deep {
    .explanation-container{
      .explanation{
        padding-left: 32px!important;
      }
    }
  }
  .revoke-img{
    position: absolute;
    width: 80px;
    height: 80px;
    right: 56px;
    top: 33px;
    z-index: 999;
  }
  .list-tab{
    margin: 16px 0;
  }
  .account-header{
    display: flex;
    margin: 32px 0 16px;
    &::v-deep {
      .el-radio{
        display: flex;
        align-items: center;
      }
    }
  }
  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 30px;
    .text {
      font-size: 14px;
      font-weight: 400;
      text-align: left;
      color: #999999;
      line-height: 20px;
      margin-top: 10px;
    }
    .blue {
      color: #406ef4;
    }
    img {
      width: 120px;
    }
  }
}
.limit-dialog {
  ::v-deep {
    .el-dialog {
      border-radius: 12px;
    }
    .el-dialog__header {
      margin: 0;
      padding: 0;
    }
    .el-dialog__body {
      padding: 0 0 24px;
    }
  }
}
.top-title {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  background-color:#fff2eb;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  margin-bottom: 24px;
  img {
    width: 24px;
    height: 24px;
    margin-right: 12px;
  }
  p {
    padding: 0;
    margin: 0;
  }
  .top-text {
    font-weight: bold;
    font-size: 16px;
    color: #333;
  }
  .top-sub-text {
    color: #FD8546;
    font-size: 12px;
  }
}
.dialog-center {
  margin-left: 52px;
  font-size: 14px;
  color: #000;
  .mb16 {
    margin-bottom: 16px;
  }
  span {
    color: #999;
  }
}
.dialog-footer {
  margin-left: 52px;
  margin-top: 24px;
}
.list-tab{
  padding: 0 !important;
}
::v-deep .el-form-item__label {
  color: #999;
}
::v-deep .el-form-item {
  margin-bottom: 0 !important;
}
::v-deep .explanation {
  margin-bottom: 0;
}
::v-deep .el-pagination {
  padding: 0 !important;
  display: flex;
  align-items: center;
}
</style>
